package com.activenetwork.custom.uielement.decorate;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.activenetwork.custom.uielement.UIElement;
import com.activenetwork.custom.uielement.XElement;
import com.activenetwork.util.EnvContext;

public class IdentifierFactory {
	private static Logger logger = LoggerFactory.getLogger(IdentifierFactory.class);

	public static By createBy(String pageName, String fieldName){
		/*
		 * Pay attention if in the .json there is no definition, it will throw RuntimeException
		 * CSS is prior to XPath
		 */
		String xpath = getXpath(pageName, fieldName);
		String css = getCss(pageName, fieldName);
		if(css != null && css.length()>0){
			logger.debug("Using css to decorate <" + pageName + "-" + fieldName + "> from json");
			return By.cssSelector(css);
		}
		if(xpath != null && xpath.length()>0){
			logger.debug("Using xpath to decorate <" + pageName + "-" + fieldName + "> from json");
			return By.xpath(xpath);
		}
		throw new RuntimeException(pageName + "-" + fieldName + " has no css or xpath defined in json");
	}
	
	public static WebElement createWebElement(String pageName, String fieldName){
		WebDriver driver = EnvContext.webDriverTL.get();
		String xpath = getXpath(pageName, fieldName);
		String css = getCss(pageName, fieldName);
		if(css != null && css.length()>0){
			return driver.findElement(By.cssSelector(css));
		}
		if(xpath != null && xpath.length()>0){
			return driver.findElement(By.xpath(xpath));
		}
		throw new RuntimeException(pageName + "-" + fieldName + " has no css or xpath defined in json");
	}
	
	public static UIElement createUIElement(String pageName, String fieldName){
		WebDriver driver = EnvContext.webDriverTL.get();
		String xpath = getXpath(pageName, fieldName);
		String css = getCss(pageName, fieldName);
		if(css != null && css.length()>0){
			return new XElement(driver.findElement(By.cssSelector(css)));
		}
		if(xpath != null && xpath.length()>0){
			return new XElement(driver.findElement(By.xpath(xpath)));
		}
		throw new RuntimeException(pageName + "-" + fieldName + " has no css or xpath defined in json");
	}
	
	private static String getCss(String pageName, String fieldName){
		try{
			return EnvContext.xpathLookup.get(pageName).get(fieldName).get("css");
		}catch(NullPointerException e){
			throw new RuntimeException("In json, pageName:"+pageName+"-fieldName:"+fieldName+" does not exist.");
		}
	}
	
	private static String getXpath(String pageName, String fieldName){
		try{
			return EnvContext.xpathLookup.get(pageName).get(fieldName).get("xpath");
		}catch(NullPointerException e){
			throw new RuntimeException("In json, pageName:"+pageName+"-fieldName:"+fieldName+" does not exist.");
		}
	}

}
